function PreViewImage(domId) {
    var value = document.getElementById(domId).value;
    if (value === '') {
        PKLayer.tipsMsg('请先上传')
    } else {
        window.open(value, '_blank');
    }
}

function dateFormat(value) {
    return PKCms.formatDateTime(value);
}

// ================ 多图片上传 列表操作
/**
 * 移除指定的 HTML 标签的 ID
 * 多文件（图片）上传的移除操作
 * @param id
 */
function remove_id(id) {
    layui.$('#' + id).remove();
}

function permutation(domId) {
    //获取表格的行
    var x = document.querySelectorAll("." + domId),
        //获取所有排序箭头
        y = document.querySelectorAll(".arrow_" + domId),
        //获取表格
        w = document.getElementById(domId);
    //点击箭头按键向上交换表格的行(li),交换之后之前的箭头按钮就不在鼠标的位置了,
    // 会再次触发排序函数02中的鼠标移出事件,运行排序函数01对i进行重新计数,
    // console.log('y:', y);
    for (var i = 0; i < x.length; i++) {
        (function (i) {
            y[2 * i].onclick = function () {
                w.insertBefore(x[i], x[i - 1]);
            };
            y[2 * i + 1].onclick = function () {
                if (x[i + 1] !== undefined) {
                    w.insertBefore(x[i + 1], x[i]);
                } else {
                    w.insertBefore(x[i], x[0]);
                }
            }
        })(i)
    }
}

//所有东西加载完之后就运行排序函数
function permutation_uploadList(domId) {
    console.log(domId);
    //获取所有排序箭头
    var y = document.querySelectorAll(".arrow_" + domId);
    console.log('y', y.length);
    for (var j = 0; j < y.length; j++) {
        //鼠标移动到任意一个箭头上就能触发排序函数01,让排序函数中的i值重新计算,不使用之前闭包内保存的值
        (function (j) {
            y[j].onmouseover = function () {
                permutation(domId);
            }
        })(j);
    }
    return false;
}

;!function (win, doc) {
    var PKAdmin = function () {
    }, config = {}, loadingJS = function (src) {
        var sobj = doc.createElement('script');
        sobj.type = "text/javascript";
        sobj.src = src;
        var headobj = doc.getElementsByTagName('head')[0];
        headobj.appendChild(sobj);
    }, localPKCMS = function () {
        loadingJS('/statics/pkcms/app/common.js');
        loadingJS('/statics/pkcms/app/layui.js');
    }, formInitParams = function () {
        var params = Object.create(null);
        if (typeof data == "object") {
            if (data.hasOwnProperty('form')) {
                params = Object.assign(params, data.form);
            }
            if (data.hasOwnProperty('init')) {
                params = Object.assign(params, data.init);
            }
        }
        return params;
    }, submitForm = function (paramsOfForm, fn, appendData) {
        // 交互的 API
        var action_form = location.pathname;
        if (typeof appendData === "object") {
            paramsOfForm = $.extend(paramsOfForm, appendData);
        }
        if (paramsOfForm.hasOwnProperty('id')) {
            if ((paramsOfForm.id == null) || (paramsOfForm.id === '') || (paramsOfForm.id == 0)) {
                action_form += '/ApiByCreate';
            } else if (location.search.indexOf('recycle') > 0) {
                action_form += '/ApiByRecycle';
            } else {
                action_form += '/ApiByChange';
            }
        } else {
            action_form += '/Api';
        }
        PKLayer.apiPost(action_form, paramsOfForm, function (result, count) {
            if (paramsOfForm.hasOwnProperty('syncUpdateTime')) {
                PKCloud.apiClientOfCloud('ServiceLink/SyncContentUpdateTime',
                    {time: result.createTime}, function (res) {
                    });
            }
            if (location.pathname.indexOf('adminLogin') > 0 || location.pathname.indexOf('AdminLogin') > 0) {
                if ((typeof result == "object") && result.hasOwnProperty('powerByAction')) {
                    // 后台管理员登陆
                    PKCms.localStorage_set(result);
                }
                setTimeout(function () {
                    location.href = '/index.php/Admin/Index';
                }, 1000);
            } else if (layui.$('[lay-filter="form-frame"]').length > 0) {
                setTimeout(function () {
                    var index = parent.layer.getFrameIndex(win.name);
                    if (typeof parent.renderTable == "function") {
                        parent.renderTable();
                    }
                    parent.layer.close(index);
                }, 200);
            } else if (layui.$('[lay-filter="form-page"]').length > 0) {
                PKLayer.tipsMsg('提交成功!');
            } else {
                fn(result, count);
            }
        });
    }, _useForm = function () {
        setTimeout(function () {
            if (layui.$('[lay-filter="form-element"]').length > 0) {
                layui.$('[lay-filter="form-element"]').removeClass('layui-disabled').removeAttr('disabled');
                PKLayer.useForm(function (paramsByForm) {
                    submitForm(paramsByForm, function (resData, resCount) {
                    });
                });
            }
        })
    }, useForm = function () {
        if (typeof $ == "function") {
            is_load_core(function () {
                _useForm();
            });
        } else {
            _useForm();
        }
    }, useFormByTpl = function (params, fn) {
        var domId_tpl = 'tpl-form', dom_tpl = layui.$('#' + domId_tpl),
            params_id = dom_tpl.data('id'), params_parent = dom_tpl.data('parent');
        if (dom_tpl.length > 0) {
            if (params_id || params_parent) {
                PKLayer.apiGet(dom_tpl.data('api') + '/ApiGetDetail',
                    params_parent ? {parent: params_parent} : {id: params_id},
                    function (res, count) {
                        PKLayer.useTplCall(res, domId_tpl, 'view-form', function (tpl) {
                            PKLayer.useFormByControlAndSubmit('form-frame', function (paramsByForm) {
                                fn(paramsByForm);
                            });
                        });
                    });
            } else {
                PKLayer.useTplCall(params, domId_tpl, 'view-form', function (tpl) {
                    PKLayer.useFormByControlAndSubmit('form-frame', function (paramsByForm) {
                        fn(paramsByForm);
                    });
                });
            }
        }
    }, useTable = function () {
        var domId = 'tplDetail-table';
        var dom = layui.$('#' + domId)
        if (dom.length === 1) {
            var data_id = dom.data('id');
            if (data_id === 0) {
            } else {
                PKLayer.apiGet(
                    dom.data('api') + '/ApiGetDetail',
                    {id: data_id},
                    function (apiResult, count) {
                        PKLayer.useTplCall(apiResult, domId, 'view-table', function (tpl) {
                            renderTable();
                        });
                    }
                );
            }
        }
    }, onTableChange = function (table, domId) {
        var dom_table = layui.$('#' + domId);
        var api_set = dom_table.data('set');
        var dom_params = dom_table.data('params');
        table.on('edit(' + domId + ')', function (obj) {
            //当前编辑的字段名
            var field = obj.field, rows = obj.data, value = obj.value;
            // console.log('obj',obj);
            var api_params = {
                id: rows.id,
            }, api_action = '';
            switch (field) {
                case 'hits':
                    api_params['hits'] = value;
                    api_action = '/ApiByHits';
                    break;
                case 'listSort':
                    api_params['sortIndex'] = value;
                    api_action = '/ApiBySortIndex';
                    break;
                case 'url':
                    api_params['url'] = value;
                    api_action = '/ApiByUrl';
                    break;
            }
            if (api_action !== '') {
                if (typeof dom_params === "string") {
                    var tmp_params = PKCms.urlVarsToJSON(dom_params);
                    api_params = Object.assign(api_params, tmp_params);
                }
                if (typeof data == "object" && data.hasOwnProperty('init')) {
                    api_params = Object.assign(api_params, data.init);
                }
                PKLayer.apiPost(api_set + api_action, api_params, function (res, count) {
                    renderTable();
                });
            }
        });
    }, useTableForm = function (domId_tpl, api_url, row_data) {
        var params = Object.assign(Object.create(null), formInitParams());
        if (typeof row_data === "object") {
            params = Object.assign(params, row_data);
        }
        PKLayer.useModelByTpl(
            $('#' + domId_tpl).data('title'), params, domId_tpl, function (index) {
                PKLayer.useFormByControlAndSubmit('form-frame', function (paramsByForm) {
                    PKLayer.apiPost(api_url, Object.assign(params, paramsByForm), function () {
                        if (typeof renderTable == "function") {
                            renderTable();
                        }
                        layer.close(index);
                    });
                });
            });
    }, onTableActionOfOpenWin = function (win_title, win_src) {
        PKLayer.useModelByFrame(win_title,
            '/index.php/' + win_src + 'frame=1');
    }, onTableActionOfDel = function (api_url, req_params) {
        var api_params = Object.assign(Object.create(null), req_params);
        if (typeof data == "object" && data.hasOwnProperty('init')) {
            api_params = Object.assign(api_params, data.init);
        }
        PKLayer.apiPost(api_url + '/ApiByDel', api_params,
            function (apiResult, count) {
                PKLayer.tipsMsg('删除成功！');
                renderTable();
            }
        );
    }, onTableToolBar = function (table, domId, isTree, initTb) {
        var dom_table = layui.$('#' + domId);
        var api_table = dom_table.data('set');
        var params_table = dom_table.data('params');
        //头工具栏事件
        table.on('toolbar(' + domId + ')', function (e) {
            var eventArr = e.event.split('|');
            // console.log('event', eventArr);
            switch (eventArr[0]) {
                case 'refresh':
                    renderTable();
                    break;
                case 'add':
                    if (eventArr.length === 3) {
                        useTableForm(eventArr[1], eventArr[2]);
                    } else if (eventArr.length === 2) {
                        useTableForm(eventArr[1], api_table + '/ApiByCreate');
                    } else {
                        PKLayer.useModelByFrame("添加",
                            '/index.php/' + dom_table.data('set') + '?' + params_table);
                    }
                    break;
                case 'batchDel':
                    PKLayer.getTableChecked(table, e, isTree, initTb, function (api_params) {
                        PKLayer.tipsConfirm(
                            '真的要批量删除么',
                            function (index) {
                                layer.close(index);
                                onTableActionOfDel(api_table ? api_table : eventArr[1], api_params);
                            });
                    });
                    break;
                case 'batchUpdateOfContext':
                    if (typeof batchUpdate == "function") {
                        PKLayer.getTableChecked(table, e, isTree, initTb, function (api_params) {
                            PKLayer.tipsConfirm(
                                '真的要批量更新么',
                                function (index) {
                                    console.log(api_params);
                                    batchUpdate(api_params.id);
                                    // layer.close(index);
                                });
                        });
                    } else {
                        console.warn('没有找到操作函数 batchUpdate');
                    }
                    break;

                case 'func':
                    var funcName = eventArr[1];
                    if (typeof (eval(funcName)) == "function") {
                        PKLayer.getTableChecked(table, e, isTree, initTb, function (api_params) {
                            var req_params = Object.assign(Object.create(null), api_params);
                            if (typeof data == "object" && data.hasOwnProperty('init')) {
                                req_params = Object.assign(req_params, data.init);
                            }
                            var s = eval(funcName + "('" + JSON.stringify(req_params) + "');");
                            // console.log(s);
                        });
                    }
                    break;

                case 'open':
                    var req_str = eventArr.length === 3 ? eventArr[2] : api_table;
                    if (req_str.indexOf('?') < 0) {
                        req_str += '?';
                    }
                    if (typeof data == "object" && data.hasOwnProperty('init')) {
                        req_str += PKCms.JSONToUrl(data.init) + '&';
                    } else {
                        req_str += '&';
                    }
                    onTableActionOfOpenWin(eventArr[1], req_str);
                    break;

                case 'setParams':
                    PKLayer.getTableChecked(table, e, isTree, initTb, function (api_params) {
                        api_params[eventArr[1]] = eventArr[2];
                        if (typeof data == "object" && data.hasOwnProperty('init')) {
                            api_params = Object.assign(api_params, data.init);
                        }
                        PKLayer.apiPost(api_table + '/ApiBy' + eventArr[1],
                            api_params, function (apiResult, count) {
                                PKLayer.tipsMsg('操作成功');
                                renderTable();
                            });
                    });
                    break;

                case 'api':
                    var api_params = {};
                    if (typeof data == "object" && data.hasOwnProperty('init')) {
                        api_params = Object.assign(api_params, data.init);
                    } else if (typeof params_table === "undefined") {
                        api_params = params_table;
                    }
                    PKLayer.apiPost(eventArr[1], api_params, function (apiResult, count) {
                        PKLayer.tipsMsg('操作成功');
                        renderTable();
                    });
                    break;

                default:
                    var func_name = eventArr[0];
                    console.log(func_name);
                    if (typeof (eval(func_name)) == "function") {
                        eval(func_name)();
                    }
                    break;
            }
        });
    }, onTableTool = function (table, domId, isTree) {
        var dom_table = layui.$('#' + domId);
        var dom_filter = dom_table.attr('lay-filter');
        var api_table = dom_table.data('set');
        var api_params = dom_table.data('params');
        if (isTree) {
            dom_filter = domId;
        }
        table.on("tool(" + dom_filter + ")",
            function (rows) {
                var eventArr = rows.event.split('|');
                var url = api_table != null ? api_table : eventArr[1];
                if (rows.data.hasOwnProperty('id')) {
                    if (url.indexOf('?') > 0) {
                        url += '&';
                    } else {
                        url += '?';
                    }
                    url += 'id=' + rows.data.id + '&frame=1';
                }
                // console.log(eventArr);
                switch (eventArr[0]) {
                    case "edit":
                        if (eventArr.length === 3) {
                            useTableForm(eventArr[1], eventArr[2], rows.data);
                        } else if (eventArr.length === 2) {
                            useTableForm(eventArr[1], api_table + '/ApiByChange', rows.data);
                        } else {
                            if (typeof api_params === "undefined") {
                                PKLayer.useModelByFrame("编辑", '/index.php/' + api_table + '?id=' + rows.data.id + '&frame=1');
                            } else {
                                PKLayer.useModelByFrame("编辑", '/index.php/' + api_table + '?' + api_params + '&id=' + rows.data.id + '&frame=1');
                            }
                        }
                        break;
                    case "del":
                        PKLayer.tipsConfirm(
                            '确定要删除ID为：' + rows.data.id + ' 数据吗？',
                            function () {
                                var params = {id: rows.data.id};
                                if (typeof api_params != "undefined") {
                                    params = Object.assign(params, PKCms.urlVarsToJSON(api_params));
                                }
                                onTableActionOfDel(api_table ? api_table : eventArr[1], params);
                            });
                        break;
                    case 'open':
                        var win_src = eventArr.length === 3 ? eventArr[2] : api_table;
                        if (win_src.indexOf('?') > 0) {
                            onTableActionOfOpenWin(eventArr[1], win_src + '&');
                        } else {
                            var tmp_src = PKCms.JSONToUrl(rows.data);
                            if (rows.data.hasOwnProperty('catId') &&
                                rows.data.hasOwnProperty('modelId') &&
                                rows.data.hasOwnProperty('id')) {
                                tmp_src = 'catId=' + rows.data.catId +
                                    '&modelId=' + rows.data.modelId +
                                    '&id=' + rows.data.id;
                            }
                            win_src += '?' + tmp_src + '&';
                            onTableActionOfOpenWin(eventArr[1], win_src);
                        }
                        break;
                    case 'api':
                        url = eventArr[1];
                        if (rows.data.hasOwnProperty('id')) {
                            PKLayer.apiGet(url, {id: rows.data.id}, function (apiResult, count) {
                                PKLayer.tipsMsg('操作成功');
                                renderTable();
                            });
                        } else {
                            PKLayer.apiPost(url, rows.data, function (res_api, count) {
                                PKLayer.tipsMsg('操作成功');
                                renderTable();
                            });
                        }
                        break;
                    case 'func':
                        var funcName = eventArr[1];
                        if (typeof (eval(funcName)) == "function") {
                            var s = eval(funcName + "('" + JSON.stringify(rows.data) + "');");
                            console.log(s);
                        }
                        break;
                    default:
                        break;
                }
            });
    }, createContentToOtherCategory = function (steps, steps_data, resData) {
        var listDom_addTo = layui.$('#addTo li');
        if (listDom_addTo.length === 0) {
            // 当没有同时发布到其他的栏目时
            steps.make(steps_data, '#steps', 3);
            setTimeout(function () {
                doneContentEditor();
            }, 200);
        } else {
            // 当同时发布到其他的栏目时
            var catList = [];
            for (var i = 0; i < listDom_addTo.length; i++) {
                var tmp_li = layui.$('#addTo li:eq(' + i + ')');
                catList.push({
                    catId: tmp_li.data('id'),
                    modelId: tmp_li.data('model')
                });
            }
            PKLayer.apiPost(
                'Content/AdminSetContent/ApiByCreateToOtherCategory',
                {
                    content: resData,
                    category: data.category,
                    catList: catList,
                    modelId: resData.modelId
                }, function (apiResult, count) {
                    steps.make(steps_data, '#steps', 3);
                    setTimeout(function () {
                        doneContentEditor();
                    }, 200);
                });
        }
    }, doneContentEditor = function () {
        var index = parent.layer.getFrameIndex(window.name);
        PKLayer.tipsConfirmByTwoBtn(
            '要刷新列表吗',
            {icon: 3, time: 30000, offset: 't', title: '提示', btn: ['确定', '取消']},
            function () {
                parent.layer.close(index);
                window.parent.renderTable();
            }, function () {
                parent.layer.close(index);
            });
    }, is_load_core = function (fn) {
        var i = setInterval(function () {
            if (typeof PKLayer == "object" && typeof $ == "function") {
                clearInterval(i);
                fn();
            }
        }, 1000);
    };

    PKAdmin.prototype.ready = function (fn) {
        if (doc.addEventListener) {
            doc.addEventListener('DOMContentLoaded', function () {
                //注销事件, 避免反复触发
                doc.removeEventListener('DOMContentLoaded', arguments.callee, false);
                //执行函数
                if (typeof PKCms == "undefined" && !win.hasOwnProperty('is_load_core')) {
                    win.is_load_core = true;
                    localPKCMS();
                }

                if (typeof PKLayer == "object" && typeof $ == "function") {
                    useForm();
                    useTable();
                    fn();
                } else {
                    is_load_core(function () {
                        useForm();
                        useTable();
                        fn();
                    });
                }
            }, false);
        } else if (doc.attachEvent) {        //IE
            doc.attachEvent('onreadystatechange', function () {
                if (doc.readyState == 'complete') {
                    doc.detachEvent('onreadystatechange', arguments.callee);
                    //函数执行
                    if (typeof PKCms == "undefined" && !win.hasOwnProperty('is_load_core')) {
                        win.is_load_core = true;
                        localPKCMS();
                    }
                    if (typeof PKLayer == "object" && typeof $ == "function") {
                        useForm();
                        useTable();
                        fn();
                    } else {
                        is_load_core(function () {
                            useForm();
                            useTable();
                            fn();
                        });
                    }
                }
            });
        }
    };

    PKAdmin.prototype.userLoginOut = function () {
        localStorage.clear();
        window.location.href = '/index.php/member/AdminLogin/out';
    }

    PKAdmin.prototype.table = function (customOptions, isPage) {
        var dom_IdAndFilter = layui.$('.PK-table').attr('lay-filter');
        PKLayer.useTable(dom_IdAndFilter, PKLayer.getTableDataOfApiPath(dom_IdAndFilter), customOptions, function (table) {
            onTableChange(table, dom_IdAndFilter);
        }, function (table) {
            onTableTool(table, dom_IdAndFilter, false);
        }, function (table) {
            onTableToolBar(table, dom_IdAndFilter, false);
        }, isPage);
    }

    PKAdmin.prototype.tableTree = function (fieldIdName, fieldPidName, customOptions, iconIndex, list_data) {
        var dom_IdAndFilter = layui.$('.PK-tableTree').attr('lay-filter');
        if (typeof dom_IdAndFilter == "undefined") {
            dom_IdAndFilter = layui.$('.PK-tableTree').attr('id');
        }
        PKLayer.useTableTree(dom_IdAndFilter, fieldIdName, fieldPidName,
            customOptions, function (table) {
                onTableChange(table, dom_IdAndFilter);
            }, function (table) {
                onTableTool(table, dom_IdAndFilter, true);
            }, function (table, insTb) {
                onTableToolBar(table, dom_IdAndFilter, true, insTb);
            }, iconIndex, list_data)
    }

    PKAdmin.prototype.selectCategoryType = function (title, callback) {
        var dom_id = 'selectCategory';
        var param;
        PKLayer.useModel(title,
            '<ul id="' + dom_id + '" class="dtree" data-id="0"></ul>',
            function (index) {
                PKLayer.useTree(dom_id, 'Content/AdminGetCategory/ApiByListsOfContent',
                    function (obj, element, dtree) {
                        param = dtree.getNowParam(dom_id);
                        console.log(param);
                    });
            }, function (index) {
                console.log('yes param id', param.nodeId);
                console.log('yes param context', param.context);
                if (param.leaf) {
                    layer.close(index);
                    callback(param);
                } else {
                    PKLayer.tipsMsg('只能选择子级栏目');
                }
            });
    }

    PKAdmin.prototype.tplFormSubmitByFn = function (params, fn, filter) {
        if (typeof filter == "undefined") {
            filter = 'form-frame';
        }
        var domId_tpl = 'tpl-form', dom_tpl = layui.$('#' + domId_tpl);
        if (dom_tpl.length > 0) {
            PKLayer.useTplCall(params, domId_tpl, 'view-form', function (tpl) {
                PKLayer.useFormByControlAndSubmit(filter, function (paramsByForm) {
                    submitForm(paramsByForm, function (resData, resCount) {
                    });
                });
                fn();
            });
        }
    }

    PKAdmin.prototype.tplFormByControl = function (filter) {
        PKLayer.useFormByControl(filter, function () {
        });
    }

    PKAdmin.prototype.tplFormSubmitInFn = function (params, fn) {
        var domId_tpl = 'tpl-form',
            dom_tpl = layui.$('#' + domId_tpl), params_id = dom_tpl.data('id');
        if (params_id) {
            PKLayer.apiGet(dom_tpl.data('api') + '/ApiGetDetail', {id: params_id}, function (res, count) {
                PKLayer.useTplCall(res, domId_tpl, 'view-form', function (tpl) {
                    fn(res);
                });
            });
        }
    }

    PKAdmin.prototype.submitFormByContent = function (paramsByForm) {
        var dom_btn = layui.$('#btnBar'), dom_steps = layui.$('#steps');
        layui.use(['steps'], function () {
            var $ = layui.$
                , steps = layui.steps
                , steps_data = [
                {'title': "第一步", "desc": "正文入库"},
                {'title': "第二步", "desc": "镜像到专题"},
                {'title': "第三步", "desc": "镜像到栏目"},
                {'title': "第四步", "desc": "完成"}
            ];
            dom_btn.hide();
            dom_steps.show();
            // data 数据
            // ele 容器
            // current 当前到了第几步
            steps.make(steps_data, '#steps', 0);
            submitForm(paramsByForm, function (resData, resCount) {
                steps.make(steps_data, '#steps', 1);
                if (data.entity.topicList.length > 0) {
                    console.log(data.entity);
                    PKLayer.apiPost(
                        'Content/AdminSetContent/ApiByCreateToTopic',
                        {
                            content: resData,
                            category: data.category,
                            topicList: data.entity.topicList,
                            modelId: resData.modelId
                        }, function (apiResult, count) {
                            steps.make(steps_data, '#steps', 2);
                            createContentToOtherCategory(steps, steps_data, resData);
                        });
                } else {
                    steps.make(steps_data, '#steps', 2);
                    createContentToOtherCategory(steps, steps_data, resData);
                }
            });
        });
    }

    PKAdmin.prototype.tplFormByTpl = function (params, fn) {
        useFormByTpl(params, function (paramsByForm) {
            fn(paramsByForm);
        });
    }

    PKAdmin.prototype.tplFormBySubmit = function (params) {
        useFormByTpl(params, function (paramsByForm) {
            submitForm(paramsByForm, function (resData, resCount) {
            });
        });
    }

    win.PKAdmin = new PKAdmin();
}(window, document);